package com.bobbygu.bobbyapp.utils.crashcatch;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bobbygu.libnet.baserx.RxManager;
import com.bobbygu.bobbyapp.base.Constant;
import com.bobbygu.bobbyapp.base.MyApplication;
import com.bobbygu.bobbyapp.base.MyBaseM;
import com.bobbygu.bobbyapp.network.HttpAction;
import com.wanjian.cockroach.Cockroach;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * CrashExceptionHandler
 * <p>
 * author: 顾博君 <br>
 * time:   2017/11/8 18:11 <br>
 * e-mail: gubojun@csii.com.cn <br>
 * </p>
 */

public class CrashExceptionHandler implements Cockroach.ExceptionHandler {
    private MyApplication application;
    private MyBaseM myBaseM = new MyBaseM();

    public CrashExceptionHandler(MyApplication application, RxManager mRxManager) {
        this.application = application;
        myBaseM.init(mRxManager);
    }

    // handlerException内部建议手动try{  你的异常处理逻辑  }catch(Throwable e){ } ，以防handlerException内部再次抛出异常，导致循环调用handlerException
    @Override
    public void handlerException(final Thread thread, final Throwable throwable) {
        //开发时使用Cockroach可能不容易发现bug，所以建议开发阶段在handlerException中用Toast谈个提示框，
        //由于handlerException可能运行在非ui线程中，Toast又需要在主线程，所以new了一个new Handler(Looper.getMainLooper())，
        //所以千万不要在下面的run方法中执行耗时操作，因为run已经运行在了ui线程中。
        //new Handler(Looper.getMainLooper())只是为了能弹出个toast，并无其他用途
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                try {
                    //建议使用下面方式在控制台打印异常，这样就可以在Error级别看到红色log
                    Log.e("AndroidRuntime", "--->CockroachException:" + thread + "<---", throwable);
                    if (application.isTrackActivities()) {
                        StringBuilder activityLogString = new StringBuilder();
                        while (!MyApplication.activityLog.isEmpty()) {
                            activityLogString.append(MyApplication.activityLog.poll());
                        }
                        Log.e(Constant.COMMON_LOG_TAG, activityLogString.toString());
                    }

                    Writer writer = new StringWriter();
                    PrintWriter pw = new PrintWriter(writer);
                    // 导出异常的调用栈信息
                    throwable.printStackTrace(pw);
                    pw.close();

                    String content = writer.toString();

                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("TagName", Constant.COMMON_LOG_TAG);
                    map.put("LogType", "error");
                    map.put("CreateTime", dateFormat.format(new Date()));
                    map.put("Content", "Exception Happend\n" + thread + "\n" + content);

                    myBaseM.post(HttpAction.Companion.getUploadAppLog(), map, new MyBaseM.SuccessCallBack() {
                        @Override
                        public void onSuccess(JSONObject jsonObject) {
                            Toast.makeText(application, "log upload success", Toast.LENGTH_SHORT).show();
                        }
                    }, new MyBaseM.ErrorCallBack() {
                        @Override
                        public void onError(String errMsg, String errCode) {
                            Toast.makeText(MyApplication.getInstance(), errMsg, Toast.LENGTH_SHORT).show();
                        }
                    });
//                    Toast.makeText(application, "Exception Happend\n" + thread + "\n" + throwable.toString(), Toast.LENGTH_SHORT).show();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
